class EventDispatcher {
    constructor() {
        this.funs = new Map();
    }
    on(type, call) {
        if (typeof type === 'Object') {
            let keys = Object.keys(type)
            if (keys.length == 0 || typeof type[0] != 'function') {
                throw new Error("参数不正确")
            }

            keys.forEach(o => {
                this.on(o, type[0])
            })

        } else {
            if (this.funs.has(type)) {
                let arr = this.funs.get(type);
                arr.add(call);
            } else {
                let arr = new Set();
                arr.add(call);
                this.funs.set(type, arr);
            }
        }

    }



    off(type, call) {
        try {
            let fns = this.funs.get(type);
            fns.delete(call);
        } catch (e) {

        }
    }

    offAll(type) {
        this.funs.get(type).clear();
    }

    emit(type, data) {
        try {
            let fns = this.funs.get(type);
            if (fns) {
                for (let f of fns.values()) {
                    f(data);
                }
            }

        } catch (e) {
            console.log(e)
        }
    }
}

module.exports = EventDispatcher;